package interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import entity.user.User;
import log.annotation.ControllerAnnotation;
import log.entity.LogForController;
import log.service.controllerlog.IControllerLogService;
import util.MYUtil;
import util.MyConfig;

/**
 * 记录controller日志
 * 
 * @author Administrator
 *
 */
public class LogInterceptor extends HandlerInterceptorAdapter {
	@Resource
	private IControllerLogService logServiceImpl;
	@Resource
	private MyConfig myConfig;

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		if (myConfig.getRecordControllerLog()) {
			if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
				ControllerAnnotation logAnnotation = ((HandlerMethod) handler).getMethodAnnotation(ControllerAnnotation.class);
				if (logAnnotation != null) {
					User user = (User) request.getSession().getAttribute("user");
					String uri = request.getRequestURI();
					String ip = request.getRemoteAddr();
					String agent = request.getHeader("User-Agent");
					String os = MYUtil.getClientOS(agent);
					String browser = MYUtil.getClientBrowser(agent);
					String app = logAnnotation.app();
					String model = logAnnotation.model();
					String function = logAnnotation.function();
					String classname = logAnnotation.classname();
					String methodname = logAnnotation.methodname();
					String opercation = logAnnotation.opercation();
					Boolean isMenu = logAnnotation.isMenu();
					String menuName = logAnnotation.menuName();
					String userId = "无";
					String username = "无";
					Boolean isError = false;
					if (ex != null) {
						isError = true;
					} else {
						userId = user.getId();
						username = user.getName();
					}
					LogForController myLog = new LogForController(app, model, function, classname, methodname, opercation, ip, username,
							browser, os, userId, agent, uri, isError,isMenu,menuName);
					try {
						logServiceImpl.save(myLog);
					} catch (Exception e) {
						MYUtil.printMyLog("---记录日志出错---", MYUtil.SHOW_SINGLE);
						e.printStackTrace();
					}
				}
			}
		}
		super.afterCompletion(request, response, handler, ex);
	}
}
